package com.zuikaku.nettychat.netty.controller;

import com.zuikaku.nettychat.service.ChatService;
import com.zuikaku.nettychat.vo.ChatVO;
import com.zuikaku.nettychat.vo.FriendVO;
import com.zuikaku.nettychat.netty.framework.BaseController;
import com.zuikaku.nettychat.netty.framework.NettyClient;
import com.zuikaku.nettychat.netty.framework.NettyServer;
import com.zuikaku.nettychat.netty.vo.MethodType;
import com.zuikaku.nettychat.pojo.Friend;
import com.zuikaku.nettychat.pojo.User;
import com.zuikaku.nettychat.service.FriendService;
import com.zuikaku.nettychat.service.UserService;
import com.zuikaku.nettychat.utils.ResponseJson;
import com.zuikaku.nettychat.utils.SendSms;
import io.netty.channel.socket.SocketChannel;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private FriendService friendService;

    @Autowired
    private ChatService chatService;

    @Autowired
    private SendSms sendSms;


    @Autowired
    private NettyServer nettyServer;


    public String sendSMS(String data, SocketChannel socketChannel){
        JSONObject requestJson = new JSONObject(data);
        String phone = requestJson.getString("phone");
        User user = userService.getUserByPhone(phone);
        if(user ==null){
            StringBuilder sb = new StringBuilder();
            while(sb.length()<6){
                sb.append((int) (Math.random() * 10));
            }
            String randomCode = sb.toString();
            JSONObject paramJson = new JSONObject();
            paramJson.put("code",randomCode);
            sendSms.send(phone,paramJson.toString(),"SMS_207755632");
            System.out.println("---:"+randomCode);
            return ResponseJson.success("短信验证码已下发",randomCode);

        }else {
            return ResponseJson.fail("电话号码已经被使用");
        }
    }

    public String register(String data,SocketChannel socketChannel){
        JSONObject requestJson = new JSONObject(data);
        User newUser =new User();

        newUser.setNick(requestJson.getString("nick"));
        newUser.setPhone(requestJson.getString("phone"));
        newUser.setPassword(requestJson.getString("password"));
        newUser.setUserName(newUser.getPhone());
        newUser.setCreateTime(new Date());
        int res = userService.addUserByUser(newUser);
        if(res>0){
            return ResponseJson.success("注册成功");
        }else {
            return ResponseJson.fail("注册失败");
        }

    }


    public String login(String data,SocketChannel socketChannel) {
        JSONObject requestJson = new JSONObject(data);
        String phone = requestJson.getString("phone");
        String password = requestJson.getString("password");
        User user = userService.getUserByPhoneAndPassword(phone,password);
        if(user!=null){
            NettyClient nettyClient = nettyServer.getSocketChannelNettyClientMap().get(socketChannel);
            nettyClient.setActiveUser(user);
            nettyClient.setLogined(true);
            return ResponseJson.success("登录成功",new JSONObject(user));

        }else {
            return ResponseJson.fail("登录失败");
        }




    }

    //模糊查询好友
    public String searchFriend(String data,SocketChannel socketChannel){
        JSONObject requestJson = new JSONObject(data);
        String nick = requestJson.getString("nick");
        List<User> userList = userService.queryUserByNick(nick);//要把自己排除掉
        userList = userList.stream().filter(p-> !p.getUserId().equals(nettyServer.getSocketChannelNettyClientMap().get(socketChannel).getActiveUser().getUserId())).collect(Collectors.toList());
        return ResponseJson.success("操作成功",new JSONArray(userList));


    }


    //添加好友申请
    public String addFriend(String data,SocketChannel socketChannel){
        JSONObject requestJson = new JSONObject(data);
        int opponentId = requestJson.getInt("opponentId");
        //当前这个用户（主动方）
        User activeUser =  nettyServer.getSocketChannelNettyClientMap().get(socketChannel).getActiveUser();


        Friend friend =new Friend();
        friend.setFkActiveId(activeUser.getUserId());
        friend.setFkPassiveId(opponentId);
        friend.setFriendStatus((byte)0);
        friend.setCreateTime(new Date());
        int res = friendService.addFriendByFriend(friend);
        // 此时需要判断对方是否处于在线，如果在线则直接主动发出响应让其做出操作(一般只有一个【目前没有去处理一个账号的多端登录】)
        List<NettyClient> opponentNettyClientList = nettyServer.getOnlineNettyClientList().stream().filter(p->p.getActiveUser().getUserId()==opponentId).collect(Collectors.toList());
        opponentNettyClientList.forEach(p->{
            SocketChannel channel = p.getSocketChannel();
            //直接调用nettyServer的方法主动发起响应（即没有SendRequest方法的Request组件）
            // 构造响应数据
            JSONObject respJsonObject = new JSONObject();
            respJsonObject.put("friendId",friend.getFriendId());//这条friend记录的主键，到时候在同意/拒绝提交时直接修改记录状态
            NettyServer.sendResponseToClient(ResponseJson.success(activeUser.getNick()+"请求添加你为好友",respJsonObject), MethodType.NOTICE_ADD_FRIEND,channel);

        });

        if(res>0){
            return ResponseJson.success("操作成功");
        }else {
            return ResponseJson.fail("操作失败");
        }
    }


    //回复好友申请
    public String replyAddFriend(String data,SocketChannel socketChannel){
        JSONObject requestJson = new JSONObject(data);
        int friendId = requestJson.getInt("friendId");
        int status = requestJson.getInt("status");
        Friend friend = friendService.getFriendByPK(friendId);
        friend.setUpdateTime(new Date());
        friend.setFriendStatus((byte)status);
        int res = friendService.updateFriendByFriend(friend);
        if(res>0){
            return ResponseJson.success("操作成功");
        }else {
            return ResponseJson.fail("操作失败");
        }


    }

    //好友列表拉取
    public String queryFriendList(String data,SocketChannel socketChannel){
        //拿到当前这个客户端持有的用户对象
        NettyClient nettyClient = nettyServer.getSocketChannelNettyClientMap().get(socketChannel);
        List<FriendVO> friendVOList = friendService.getFriendVOByUserId(nettyClient.getActiveUser().getUserId());
        return ResponseJson.success("操作成功",new JSONArray(friendVOList));

    }

    //聊天列表拉取
    public String queryChatList(String data,SocketChannel socketChannel){
        NettyClient nettyClient = nettyServer.getSocketChannelNettyClientMap().get(socketChannel);
        List<ChatVO> chatVOList = chatService.getChatVOByUserId(nettyClient.getActiveUser().getUserId());
        return ResponseJson.success("操作成功",new JSONArray(chatVOList));
    }



}
